<?php
	namespace core;
	use Illuminate\Database\Capsule\Manager as DbManager;
	class App{
		/**动态存放调用的实例Bean*/
		private static $allBeans = array();
		
		static function getCurrentUser(){
			$user = self::session('user');
			return $user;
		}
		static function get($name=null){
			if(!is_null($name)){
				if($_GET[$name]!=null) return $_GET[$name];
				return null;
			}
			if(isset($_GET)){
				return array_filter($_GET,function($val){
					if($val!=null) return true;
					else return false;
				});
			}
			return array();
		}
		
		static function form($name=null){
			if(!is_null($name))
				return self::get($name)?:self::post($name);
			else{
				return array_merge(self::get(),self::post());
			}	
		}
		
		static function post($name=null){
			if(!is_null($name)){
				if($_POST[$name]!=null) return $_POST[$name];
				return null;
			}
			
			if(isset($_POST)){
				return array_filter($_POST,function($val){
					if($val!=null) return true;
					else return false;
				});
			}
			return array();
		}
		
		static function session($name=null,$value=false){
			if(!is_null($name)){
				if(is_null($value)) unset($_SESSION[$name]);
				else{
					if($value==false){
						if(isset($_SESSION[$name]))
							return $_SESSION[$name];
						else return null;
					}else $_SESSION[$name] = $value;
				}
			}
			return $_SESSION;
		}
		
		static function cookie($name=null,$value=false){
			if(!is_null($name)){
				if(is_null($value)) unset($_COOKIE[$name]);
				else{
					if($value==false){
						if(isset($_COOKIE[$name]))
							return $_COOKIE[$name];
						else return null;
					}
					else $_COOKIE[$name] = $value;
				}
			}
			return $_COOKIE;
		}
		
		function redirect($url){
			if(!Util::startWith($url,'http')){
				header("location:".CONTEXT_PATH.$url);
			}else{
				header("location:".$url);
			}
		}
		
		/**动态加载class：$class类的全称，$isNew是否产生新实例*/
		static function bean($class,$isNew=false){
			//返回已存在的实例
			if(!$isNew&&array_key_exists($class,self::$allBeans)){
				return self::$allBeans[$class];
			}
			//service--注入魔术类型事务类
			if(get_parentClassName($class)=='core\BaseService'){
				$instance = new \core\Transaction(create_class($class));
			}else{
				$instance = create_class($class);
			}
			
			//保存单例实例
			if(!$isNew&&!array_key_exists($class,self::$allBeans)){
				self::$allBeans[$class]=$instance;
			}
			return $instance;
		}
		
		static function schema(){
			return DbManager::schema();
		}
		
		static function table($table){
			return DbManager::table($table);
		}
		
		static function DB(){
			return DbManager::connection();
		}
	}